﻿// <copyright file="TotalOpportunities.cs" company="">
// Copyright (c) 2014 All Rights Reserved
// </copyright>
// <author></author>
// <date>3/26/2014 9:19:13 PM</date>
// <summary>Implements the TotalOpportunities Workflow Activity.</summary>
namespace Xrm.Solutions.FrameworkSample.Workflow
{
    using System;
    using System.Activities;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Workflow;
    using Xrm.Solutions.FrameworkSample.Common.Entities;
    using System.Linq;

    /// <summary>
    /// Calculates the total value of an account based on its related opportunities
    /// </summary>
    public class TotalOpportunities : BaseCodeActivity
    {
        #region Input Parameters

        [Input("Account")]
        [ReferenceTarget("account")]
        public InArgument<EntityReference> AccountReference { get; set; }

        #endregion

        #region Output Parameters

        [Output("Total")]
        public OutArgument<Money> Total { get; set; }

        #endregion

        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void ExecuteActivity(CodeActivityContext executionContext)
        {
            Guid accountId = AccountReference.Get(executionContext).Id;
            decimal total = 0;

            using (XrmServiceContext myContext = new XrmServiceContext(this.OrganizationService))
            {
                var opps = from opp in myContext.OpportunitySet
                            where opp.AccountId.Id == accountId
                            select opp.ActualValue;

                base.TracingService.Trace("Opportunities have been retrieved");

                foreach (Money actual in opps)
                {
                    total += actual.Value; 
                }
            }

            Total.Set(executionContext, new Money(total));
        }
    }
}